package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.config.KafkaConfig;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.status.CheckStatusEnum;
import com.bwie.utils.R;
import com.bwie.vo.LoginAdminVo;
import com.bwie.vo.LoginForm;
import com.bwie.vo.PageInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sun.media.sound.SoftTuning;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author Lenovo
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-04-20 18:42:41
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    FastFileStorageClient fastFileStorageClient;
    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public R getUserByUserId(Integer userId) {
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser == null){
            return R.ERROR(404,"该用户不存在");
        }
        return R.OK(tbUser);
    }

    @Override
    public R login(LoginAdminVo loginAdminVo) {

        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserName, loginAdminVo.getUserName())
        );
        if(tbUser == null){
            return R.ERROR(404,"该用户不存在");
        }

        if(!tbUser.getUserPass().equals(loginAdminVo.getUserPass())){
            return R.ERROR(500,"密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("nickName", tbUser.getNickName())
                .compact();
        String tokenKey = "token-"+tbUser.getUserId();
        redisTemplate.opsForValue().set(tokenKey,token,15, TimeUnit.MINUTES);

        tbUser.setUserPass(null);
        tbUser.setToken(token);

        return R.OK(tbUser);
    }

    @Override
    public R loginMobile(LoginForm loginForm) {
        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, loginForm.getUserMobile())
        );
        if(tbUser == null){
            return R.ERROR(404,"手机号不存在");
        }

        String redisCode = redisTemplate.opsForValue().get(tbUser.getUserMobile());
        if(redisCode == null){
            return R.ERROR(404,"验证码失效");
        }
        if(!redisCode.equals(loginForm.getCode())){
            return R.ERROR(500,"验证码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userMobile", tbUser.getUserMobile())
                .claim("nickName", tbUser.getNickName())
                .compact();

        String tokenKey = "token-" + tbUser.getUserId();
        redisTemplate.opsForValue().set(tokenKey,token,15,TimeUnit.MINUTES);

        tbUser.setUserPass(null);
        tbUser.setToken(token);

        String msg = JSON.toJSONString(tbUser);
        kafkaTemplate.send(KafkaConfig.TOPIC_LOGIN,msg);
        System.out.println("kafka消息发送成功："+msg);

        return R.OK(tbUser);
    }

    @KafkaListener(topics = KafkaConfig.TOPIC_LOGIN)
    public void loginListener(String msg, Acknowledgment acknowledgment){
        System.out.println("kafka接收消息成功："+msg);

        acknowledgment.acknowledge();
    }

    @Override
    public R sendCode(String mobile) {
        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, mobile)
        );
        if(tbUser == null){
            return R.ERROR(404,"手机号不存在");
        }

        String code = RandomUtil.randomNumbers(4);
        redisTemplate.opsForValue().set(mobile,code,15,TimeUnit.MINUTES);
        
        return R.OK(code);
    }

    @Override
    public R addUser(TbUser tbUser) {
        TbUser user = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getNickName, tbUser.getNickName())
        );
        if(user != null){
            return R.ERROR(500,"该姓名已存在");
        }

        tbUser.setCreateTime(new Date());
        tbUser.setCheckStatus(CheckStatusEnum.WAIT.getCode());
        tbUserMapper.insert(tbUser);
        return R.OK();
    }

    @Override
    public R getUserPage(PageInfoVo pageInfoVo) {
        Page<TbUser> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

//        LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();

//        if(StringUtils.isNotBlank(pageInfoVo.getKeyWord())){
//            wrapper.like(TbUser::getUserName,pageInfoVo.getKeyWord())
//                    .or()
//                    .like(TbUser::getNickName,pageInfoVo.getKeyWord())
//                    .or()
//                    .like(TbUser::getUserMobile,pageInfoVo.getKeyWord())
//                    .or()
//                    .like(TbUser::getUserEmail,pageInfoVo.getKeyWord());
//        }

        Page<TbUser> tbUserPage = tbUserMapper.selectUserPage(page, pageInfoVo);
        return R.OK(tbUserPage);
    }

    @Override
    public R loadImage(MultipartFile file) {

        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            if(storePath == null){
                return R.ERROR(404,"上传失败");
            }

            String url = "http://192.168.80.192:8888/"+storePath.getFullPath();
            System.out.println("图片路径："+url);
            return R.OK(url);
        } catch (IOException e) {
            e.printStackTrace();
            return R.ERROR(500,"上传失败");
        }
    }

    @Override
    public R checkUser(TbUser tbUser) {
        //审核驳回
        if(tbUser.getCheckStatus() == 2){
            if(StringUtils.isEmpty(tbUser.getCheckReason())){
                return R.ERROR(500,"驳回原因不能为空");
            }
            tbUser.setCheckStatus(CheckStatusEnum.REFUSE.getCode());
            tbUserMapper.updateById(tbUser);
        }

        //审核通过
        if(tbUser.getCheckStatus() == 1){
            tbUser.setCheckStatus(CheckStatusEnum.PASS.getCode());
            tbUserMapper.updateById(tbUser);
        }

        return R.OK();
    }

    @Override
    public R updateUser(TbUser tbUser) {
        TbUser user = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserId, tbUser.getUserId())
        );
        if(user == null){
            return R.ERROR(404,"该用户不存在");
        }

        tbUserMapper.updateById(tbUser);
        return R.OK();
    }

    @Override
    public R deleteByUserId(Integer userId) {
        TbUser user = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserId, userId)
        );
        if(user == null){
            return R.ERROR(404,"该用户不存在");
        }

        tbUserMapper.deleteById(userId);
        return R.OK();
    }

    @Override
    public R deleteBatch(List<TbUser> ids) {
        if(ids.size() == 0){
            return R.ERROR(500,"请先选择要删除的数据");
        }
        for (TbUser id : ids) {
            tbUserMapper.deleteById(id);
        }
        return R.OK();
    }


}




